import { reactive, onMounted, ref, nextTick } from 'vue'
/**
 * 1 阶段数据 2 模板数据
 */
import { stagePageApi, checklistAnalysePageApi, checklistAnalyseAddApi, checklistRemoveApi } from '@/api/01work/01stage'
import { StageList, StageTable, CheckListAdd, CheckListNameAndTem } from '@/api/01work/01type'
import { EditType } from '@/type/BaseEnum'
import useInstance from '@/hooks/useInstance';
import { Result, StatusCode } from '@/utils/request';

export default function getBasicData() {
  //  阶段查询数据
  const { global, proxy } = useInstance();
  const RefTemplate = ref<{ show: (type: string, row?: CheckListAdd) => void }>()
  const stageParams = reactive<StageList>({
    page: 1,
    size: 100,
    name: ''
  })
  const tableHeigth = ref(0)
  let salanyId = ref<string|number>('')
  let stageTableData = reactive<any>({
    list: [],
    table: [],
    Loading: false
  })
  // ref 准备 
  const addBtn = () => {
    console.log('add');
    RefTemplate.value?.show(EditType.ADD)
  }
  onMounted(() => {
    getStageList()
    nextTick(() => {
      // 929-856 = 73 + 20 + 50 +42 = 112+73 = 185
      tableHeigth.value = window.innerHeight - 245
    })
  })
  const getStageList = async () => {
    const res = await stagePageApi(stageParams)
    console.log(res);
    if (res.code === 200) {
      stageTableData.list = res.data.records
      if (res.data.records.length > 0) {
        getCheckListPage(res.data.records[0].id)
      }
    }
  }
  const getCheckListPage = async (id: number | string) => {
    salanyId.value = id 
    stageTableData.Loading = true
    console.log(id,'-----');
    
    const res = await checklistAnalysePageApi(id)
    if (res.code === 200) {
      stageTableData.Loading = false
      stageTableData.table = res.data
    }
  }
  const save = async (params: CheckListAdd) => {
    let res
    if (!params.id) {
      res = await checklistAnalyseAddApi(params)

    }
    if (res.code === 200 && !params.id) {
      global.$message({ message: '新增成功', type: 'success' })
      getCheckListPage(params.stageId)
    }
  }
  const editBtn = (params: CheckListAdd) => {
    console.log('btnedit', RefTemplate);
    RefTemplate.value?.show(EditType.EDIT, params)
  }
  const deleteBtn = async (id: number|string) => {
    const params = {
      id:id,
      type:0
    }
    const confirm =await global.$myconfirm('你确定需要删除嘛?')
    if (confirm) {
      const res = await checklistRemoveApi(params)
      if (res.code === 200) {
        global.$message({ message: '删除成功', type: 'success' })
        getCheckListPage(salanyId.value)
      }
    }else{
      global.$message({message:'已取消删除',type:'warning'})
    }

  }
  return {
    getStageList, stageTableData, getCheckListPage, tableHeigth, addBtn, save, editBtn, deleteBtn,
    RefTemplate
  }
}